package cn.iocoder.yudao.module.spark.util;

import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.module.digital.controller.admin.competition.vo.CompetitionSaveReqVO;
import cn.iocoder.yudao.module.digital.controller.admin.csc.vo.CscSaveReqVO;
import cn.iocoder.yudao.module.digital.controller.admin.projects.vo.ProjectsSaveReqVO;
import cn.iocoder.yudao.module.digital.controller.admin.thesis.vo.ThesisSaveReqVO;
import cn.iocoder.yudao.module.system.dal.dataobject.user.AdminUserDO;
import cn.iocoder.yudao.module.system.dal.mysql.user.AdminUserMapper;
import okhttp3.HttpUrl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Component
public class ApiAuthUtil {
    @Autowired
    private AdminUserMapper adminUserMapper;

    public String getSignature(String appId, String secret, long ts) {
        try {
            String auth = md5(appId + ts);
            return hmacSHA1Encrypt(auth, secret);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private String hmacSHA1Encrypt(String text, String key) throws Exception {
        SecretKeySpec secretKey = new SecretKeySpec(key.getBytes(StandardCharsets.UTF_8), "HmacSHA1");
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(secretKey);
        byte[] rawHmac = mac.doFinal(text.getBytes(StandardCharsets.UTF_8));
        return java.util.Base64.getEncoder().encodeToString(rawHmac);
    }

    private String md5(String text) throws Exception {
        MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] bytes = md.digest(text.getBytes(StandardCharsets.UTF_8));
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) sb.append(String.format("%02x", b & 0xff));
        return sb.toString();
    }

    // 工具方法：读取文件为byte[]
    public byte[] readFile(String filePath) throws IOException {
        try (InputStream in = new FileInputStream(filePath);
             ByteArrayOutputStream out = new ByteArrayOutputStream()) {
            byte[] buffer = new byte[4096];
            int n;
            while ((n = in.read(buffer)) != -1) {
                out.write(buffer, 0, n);
            }
            return out.toByteArray();
        }
    }
    // 鉴权方法
    public String getAuthUrl(String hostUrl, String apiKey, String apiSecret) throws Exception {
        URL url = new URL(hostUrl);
        // 时间
        SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
        format.setTimeZone(TimeZone.getTimeZone("GMT"));
        String date = format.format(new Date());
        // 拼接
        String preStr = "host: " + url.getHost() + "\n" +
                "date: " + date + "\n" +
                "GET " + url.getPath() + " HTTP/1.1";
        // SHA256加密
        Mac mac = Mac.getInstance("hmacsha256");
        SecretKeySpec spec = new SecretKeySpec(apiSecret.getBytes(StandardCharsets.UTF_8), "hmacsha256");
        mac.init(spec);
        byte[] hexDigits = mac.doFinal(preStr.getBytes(StandardCharsets.UTF_8));
        // Base64加密
        String sha = Base64.getEncoder().encodeToString(hexDigits);
        // 拼接
        String authorization = String.format("api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"",
                apiKey, "hmac-sha256", "host date request-line", sha);
        // 拼接地址
        HttpUrl httpUrl = Objects.requireNonNull(HttpUrl.parse("https://" + url.getHost() + url.getPath())).newBuilder()
                .addQueryParameter("authorization", Base64.getEncoder().encodeToString(authorization.getBytes(StandardCharsets.UTF_8)))
                .addQueryParameter("date", date)
                .addQueryParameter("host", url.getHost())
                .build();
        return httpUrl.toString();
    }

    //将返回结果转为map集合
    public Map<String, String> parseToMap(String input) {
        Map<String, String> map = new HashMap<>();
        String[] lines = input.split("\\n");
        for (String line : lines) {
            String[] kv = line.split("：", 2);
            if (kv.length == 2) {
                map.put(kv[0].trim(), kv[1].trim());
            }
        }
        return map;
    }


    //将map封装为CompetitionRespVO
    public CompetitionSaveReqVO mapToCompetitionRespVO(Map<String, String> map, List<String> evidenceUrl) {
        CompetitionSaveReqVO vo = new CompetitionSaveReqVO();
        vo.setName(map.get("竞赛名字"));
        vo.setType(parseInt(map.get("比赛级别")));
        vo.setOrganizerOther(map.get("主办方"));
        vo.setLevel(parseInt(map.get("获奖级别")));
        String members = map.get("全部指导老师");
        List<String> nicknameList = Arrays.asList(members.trim().split("\\s+"));
        List<AdminUserDO> userList = adminUserMapper.selectList(
                new LambdaQueryWrapperX<AdminUserDO>()
                        .in(AdminUserDO::getNickname, nicknameList)
                        .select(AdminUserDO::getId)
        );
        List<Long> userIdList = userList.stream()
                .map(AdminUserDO::getId)
                .collect(Collectors.toList());
        if (userIdList != null && !userIdList.isEmpty()) {
            vo.setAuthor(String.valueOf(userIdList.get(0)));
            vo.setMember(String.valueOf(userIdList));
        }
        else {
            vo.setAuthor(map.get("全部指导老师"));
            vo.setMember(map.get("全部指导老师"));
        }
        vo.setRank(parseInt(map.get("奖项")));
        vo.setReserved1(map.get("作品名称"));
        vo.setEvidenceUrl(evidenceUrl);
        vo.setReserved2(map.get("参赛学生"));
        // 获奖时间转为LocalDateTime
        if (map.get("获奖时间") != null) {
            vo.setCompetitionTime(LocalDateTime.parse(map.get("获奖时间")));
        }
        // 其他字段可根据需要补充
        return vo;
    }

    //将map封装为ProjectsSaveReqVO
    public ProjectsSaveReqVO mapToProjectsSaveReqVO(Map<String, String> map, List<String> evidenceUrl) {
        ProjectsSaveReqVO vo = new ProjectsSaveReqVO();
        vo.setName(map.get("项目名称"));
        vo.setType(1);
        vo.setOrganizer(5);
        vo.setLevel(parseInt(map.get("级别")));
        vo.setStatus(2);
        String members = map.get("成员");
        List<String> nicknameList = Arrays.asList(members.trim().split("\\s+"));
        List<AdminUserDO> userList = adminUserMapper.selectList(
                new LambdaQueryWrapperX<AdminUserDO>()
                        .in(AdminUserDO::getNickname, nicknameList)
                        .select(AdminUserDO::getId)
        );
        List<Long> userIdList = userList.stream()
                .map(AdminUserDO::getId)
                .collect(Collectors.toList());
        if (userIdList != null && !userIdList.isEmpty()) {
            vo.setAuthor(String.valueOf(userIdList.get(0)));
            vo.setMember(String.valueOf(userIdList));
        }
        else {
            vo.setAuthor(map.get("成员"));
            vo.setMember(map.get("成员"));
        }
        vo.setReserved1(map.get("项目名称"));
        vo.setEvidenceUrl(evidenceUrl);
        // 获奖时间转为LocalDateTime
        if (map.get("立项时间") != null) {
            vo.setProjectStartTime(LocalDateTime.parse(map.get("立项时间")));
        }
        if (map.get("结项时间") != null) {
            vo.setProjectEndTime(LocalDateTime.parse(map.get("结项时间")));
        }
        // 其他字段可根据需要补充
        return vo;
    }

    private Integer parseInt(String s) {
        try {
            return s == null ? null : Integer.parseInt(s);
        } catch (Exception e) {
            return null;
        }
    }

    public ThesisSaveReqVO mapToThesisSaveReqVO(Map<String, String> map, List<String> evidenceUrl) {
        ThesisSaveReqVO vo = new ThesisSaveReqVO();
        vo.setTitle(map.get("论文标题"));
        vo.setType(parseInt(map.get("论文类型")));
        vo.setAuthorType(parseInt(map.get("作者类型")));
        vo.setAuthor(map.get("作者"));
        vo.setAffiliation(parseInt(map.get("所属单位")));
        vo.setPublications(map.get("发表刊物/论文集"));
        vo.setEvidenceUrl(evidenceUrl);
        // 获奖时间转为LocalDateTime
        if (map.get("发表时间") != null) {
            vo.setPostedTime(LocalDateTime.parse(map.get("发表时间")));
        }
        // 其他字段可根据需要补充
        return vo;
    }

    public CscSaveReqVO mapToCscSaveReqVO(Map<String, String> map, List<String> evidenceUrl) {
        CscSaveReqVO vo = new CscSaveReqVO();
        vo.setName(map.get("著作权名称"));
        vo.setNo(map.get("编号"));
        vo.setRegistrationNum(map.get("登记号"));
        vo.setAuthor(map.get("作者"));
        vo.setCscType(parseInt(map.get("著作权类型")));
        vo.setEvidenceUrl(evidenceUrl);
        vo.setAffiliation(0);
        // 获奖时间转为LocalDateTime
        if (map.get("出版日期") != null) {
            vo.setPublicationTime(LocalDateTime.parse(map.get("出版日期")));
        }
        // 其他字段可根据需要补充
        return vo;
    }
}